<template>
  <div class="register-container">
    <div class="links">
      <a href="/login">登录</a>
      <a href="/forgot">忘记密码</a>
    </div>
    <form @submit.prevent="register">
      <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="user.username" required />
      </div>
      <div>
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="user.password" required />
      </div>
      <div>
        <label for="confirm-password">确认密码:</label>
        <input type="password" id="confirm-password" v-model="user.confirmPassword" required />
        <p v-if="passwordMismatch" style="color: red;">两次密码不匹配.</p>
      </div>
      <div>
        <label for="email">邮箱:</label>
        <input type="email" id="email" v-model="user.email" @input="validateEmail" required />
        <p v-if="!emailValid && user.email" style="color: red;">不合法的邮箱格式.</p>
      </div>
      <div class="verification-container">
        <input type="text" id="verification-code" v-model="verificationCode" @input="validateVerificationCode" required />
        <p v-if="verificationCodeError" style="color: red;">验证码必须为6位有效数字.</p>
        <button type="button" class="verification-button" @click="sendVerificationEmail" :disabled="isSendButtonDisabled">
            {{ countdown > 0 ? `${countdown}s后重发` : '发送验证码' }}
        </button>
      </div>
      <button type="submit" :disabled="!isFormValid">注册</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';
import Swal from 'sweetalert2';
export default {
  data() {
    return {
      user: {
        username: '',
        password: '',
        confirmPassword: '',
        email: ''
      },
      verificationCode: '',
      verificationCodeError: false,
      countdown: 0,
      errorMessage: '',
      emailValid: false
    };
  },
  computed: {
    passwordMismatch() {
      return this.user.password && this.user.confirmPassword && this.user.password !== this.user.confirmPassword;
    },
    isFormValid() {
      return !this.passwordMismatch && this.emailValid && this.verificationCode.length === 6;
    },
    isSendButtonDisabled() {
      return !this.emailValid || this.countdown > 0;
    }
  },
  methods: {
    validateEmail() {
      if (this.user.email == '') {
        this.emailValid = true;
      }
      const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      this.emailValid = emailPattern.test(this.user.email);
    },

    validateVerificationCode() {
      this.verificationCodeError = this.verificationCode.length !== 6;
    },

    async register() {
      try {
        const payload = {
          username: this.user.username,
          password: this.user.password,
          email: this.user.email,
          code : this.verificationCode
        };
        
        const response = await fetch('http://8.219.49.219:8080/onlineShopping/user/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept' : 'application/json'
          },
          credentials : 'include',
          body: JSON.stringify(payload)
        }).then(response => response.json())
          .then(data => {
            //console.log(data)
            if (data.code == 200 && data.message == '请求成功' && data.data == '注册成功') {
              Swal.fire({
                icon: 'success',
                title: '注册成功',
                text: '恭喜您已成功注册！',
                showConfirmButton: true,
                confirmButtonText: '去登录'
              }).then((result) => {
                if (result.isConfirmed) {
                  this.$router.push('/login');
                }
              });       
            } else {
              Swal.fire({
              icon: 'error',
              title: '注册失败',
              text: '验证码错误或验证码已过期'
              });
            }
          })
         
      } catch (error) {
        console.error('Error during registration:', error);
        // SweetAlert2 错误提示
        Swal.fire({
          icon: 'error',
          title: '注册失败',
          text: '注册过程中发生错误，请重试'
        });
      }
  },
    async sendVerificationEmail() {
      try {
        //console.log(this.user.email)
        const response = await axios.post('http://8.219.49.219:8080/onlineShopping/user/sendEmail', {

            email: this.user.email
        }, {
          withCredentials: true
        });
        //console.log(response)
        this.startCountdown();
      } catch (error) {
        this.errorMessage = '发送邮件失败，请重试。';
      }
    },
    startCountdown() {
      this.countdown = 60;
      const interval = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(interval);
        }
      }, 1000);
    }
  },
  watch: {
    email(newEmail) {
      this.validateEmail();
    }
  }
};
</script>

<style scoped>
.register-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  color: #333;
  background-image: url('/pictures/bg.jpg');
  background-size: cover;
  background-position: center;
  background-blend-mode: multiply;
}

.register-container h2 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
  font-family: 'Roboto', sans-serif;
}

.form-group {
  margin-bottom: 20px;
  text-align: left;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-size: 16px;
  color: #666;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  background-color: #f8f8f8;
  color: #333;
  box-sizing: border-box;
}

button {
  width: 100%;
  padding: 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

button[type="submit"] {
  margin-top: 20px; 
}

.links {
  margin-top: 20px;
  text-align: center;
}

.links a {
  margin: 0 10px;
  color: #4CAF50;
  text-decoration: none;
  font-size: 16px;
}

.links a:hover {
  text-decoration: underline;
}

form > div {
  margin-bottom: 20px; 
}

label {
  display: block;
  margin-bottom: 5px;
  color: #333;
}

input[type="text"],
input[type="password"],
input[type="email"] {
  width: 68%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

p {
  margin-top: 5px;
  text-align: left;
  color: #ff0000;
}

.verification-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.verification-container input {
  width: 70%; 
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

.verification-button {
  width: 28%; 
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  transition: background-color 0.3s ease;
  margin-left: 10px;
}

.verification-button:hover {
  background-color: #45a049;
}

.verification-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.verification-container p {
  margin-top: 5px;
  text-align: left;
  color: #ff0000;
}

</style>
